<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <text class="title">校园餐饮</text>
      <view class="right-btn" @tap="goToOrders">
        <text class="iconfont icon-order"></text>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <text class="search-icon iconfont icon-search"></text>
      <input type="text" class="search-input" placeholder="搜索菜品、食堂" @input="onSearchInput" />
    </view>

    <!-- 食堂选择标签 -->
    <scroll-view scroll-x class="canteen-tabs" show-scrollbar="false">
      <view 
        class="canteen-tab" 
        v-for="(item, index) in canteens" 
        :key="index"
        :class="{ active: currentCanteen === item.id }"
        @tap="switchCanteen(item.id)"
      >
        <text>{{ item.name }}</text>
      </view>
    </scroll-view>

    <!-- 餐点类别 -->
    <scroll-view scroll-x class="meal-tabs" show-scrollbar="false">
      <view 
        class="meal-tab" 
        v-for="(item, index) in mealTypes" 
        :key="index"
        :class="{ active: currentMealType === item.id }"
        @tap="switchMealType(item.id)"
      >
        <text>{{ item.name }}</text>
      </view>
    </scroll-view>

    <!-- 食品分类列表 -->
    <view class="food-category-container">
      <!-- 左侧分类导航 -->
      <scroll-view scroll-y class="category-sidebar">
        <view 
          class="category-item" 
          v-for="(item, index) in foodCategories" 
          :key="index"
          :class="{ active: currentCategory === item.id }"
          @tap="switchCategory(item.id)"
        >
          <text>{{ item.name }}</text>
        </view>
      </scroll-view>
      
      <!-- 右侧食品列表 -->
      <scroll-view scroll-y class="food-list-scroll" @scrolltolower="loadMoreFood">
        <view class="category-title">{{ getCurrentCategoryName() }}</view>
        
        <view class="food-list">
          <view class="food-item" v-for="(item, index) in foodList" :key="index" @tap="goToFoodDetail(item)">
            <image :src="item.imageUrl" mode="aspectFill" class="food-image"></image>
            <view class="food-info">
              <view class="food-name">{{ item.name }}</view>
              <view class="food-tags" v-if="item.tags && item.tags.length">
                <text class="food-tag" v-for="(tag, tagIndex) in item.tags" :key="tagIndex">{{ tag }}</text>
              </view>
              <view class="food-desc">{{ item.description }}</view>
              <view class="food-bottom">
                <view class="food-price">¥{{ item.price }}</view>
                <view class="food-sales">月售{{ item.monthlySales }}份</view>
              </view>
              <view class="add-btn" @tap.stop="addToCart(item)">
                <text class="iconfont icon-add"></text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <view class="loading-more" v-if="loading">加载中...</view>
        <view class="no-more" v-if="!hasMore && foodList.length > 0">没有更多了</view>
        <view class="empty-list" v-if="foodList.length === 0 && !loading">
          <image src="http://101.37.17.240:9000/zhxy/empty-menu.png" mode="aspectFit" class="empty-image"></image>
          <text>当前分类暂无菜品</text>
        </view>
      </scroll-view>
    </view>

    <!-- 购物车 -->
    <view class="cart-bar" v-if="cartTotal > 0">
      <view class="cart-info" @tap="showCart">
        <view class="cart-icon-wrapper">
          <text class="iconfont icon-cart"></text>
          <view class="cart-badge">{{ cartItemCount }}</view>
        </view>
        <view class="cart-price">¥{{ cartTotal.toFixed(2) }}</view>
      </view>
      <view class="checkout-btn" @tap="goToCheckout">
        <text>去结算</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 搜索关键词
      searchKeyword: '',
      
      // 食堂列表
      canteens: [
        { id: 'all', name: '全部食堂' },
        { id: 'canteen1', name: '第一食堂' },
        { id: 'canteen2', name: '第二食堂' },
        { id: 'canteen3', name: '第三食堂' },
        { id: 'canteen4', name: '教工食堂' },
        { id: 'cafe', name: '咖啡厅' }
      ],
      currentCanteen: 'all',
      
      // 餐点类型
      mealTypes: [
        { id: 'all', name: '全部时段' },
        { id: 'breakfast', name: '早餐' },
        { id: 'lunch', name: '午餐' },
        { id: 'dinner', name: '晚餐' },
        { id: 'snack', name: '小吃' }
      ],
      currentMealType: 'all',
      
      // 食品分类
      foodCategories: [
        { id: 'all', name: '全部' },
        { id: 'rice', name: '米饭套餐' },
        { id: 'noodle', name: '面食' },
        { id: 'soup', name: '汤类' },
        { id: 'snack', name: '小吃' },
        { id: 'drink', name: '饮品' },
        { id: 'vegetable', name: '素菜' },
        { id: 'meat', name: '荤菜' },
        { id: 'special', name: '特色菜' }
      ],
      currentCategory: 'all',
      
      // 食品列表
      foodList: [
        {
          id: 1,
          name: '红烧牛肉饭',
          description: '精选牛肉，配以秘制酱料，搭配时令蔬菜',
          price: 15.00,
          originalPrice: 18.00,
          imageUrl: 'http://101.37.17.240:9000/zhxy/food1.jpg',
          tags: ['热销', '特价'],
          canteenId: 'canteen1',
          categoryId: 'rice',
          mealTypeId: 'lunch',
          monthlySales: 238,
          rating: 4.8
        },
        {
          id: 2,
          name: '番茄鸡蛋面',
          description: '面条劲道爽滑，番茄酸甜可口',
          price: 12.00,
          originalPrice: 12.00,
          imageUrl: 'http://101.37.17.240:9000/zhxy/food2.jpg',
          tags: ['招牌'],
          canteenId: 'canteen1',
          categoryId: 'noodle',
          mealTypeId: 'lunch',
          monthlySales: 186,
          rating: 4.6
        },
        {
          id: 3,
          name: '黄焖鸡米饭',
          description: '鸡肉鲜嫩多汁，米饭香软可口',
          price: 14.00,
          originalPrice: 14.00,
          imageUrl: 'http://101.37.17.240:9000/zhxy/food3.jpg',
          tags: ['推荐'],
          canteenId: 'canteen2',
          categoryId: 'rice',
          mealTypeId: 'lunch',
          monthlySales: 210,
          rating: 4.7
        },
        {
          id: 4,
          name: '麻辣香锅',
          description: '多种食材混合烹饪，麻辣鲜香',
          price: 18.00,
          originalPrice: 20.00,
          imageUrl: 'http://101.37.17.240:9000/zhxy/food4.jpg',
          tags: ['辣'],
          canteenId: 'canteen2',
          categoryId: 'special',
          mealTypeId: 'dinner',
          monthlySales: 245,
          rating: 4.9
        },
        {
          id: 5,
          name: '盖浇饭',
          description: '现炒菜品浇在米饭上，一碗两吃',
          price: 12.00,
          originalPrice: 12.00,
          imageUrl: 'http://101.37.17.240:9000/zhxy/food5.jpg',
          tags: [],
          canteenId: 'canteen3',
          categoryId: 'rice',
          mealTypeId: 'lunch',
          monthlySales: 156,
          rating: 4.5
        },
        {
          id: 6,
          name: '鸡汤面',
          description: '鸡汤熬制8小时，面条筋道爽滑',
          price: 13.00,
          originalPrice: 13.00,
          imageUrl: 'http://101.37.17.240:9000/zhxy/food6.jpg',
          tags: [],
          canteenId: 'canteen3',
          categoryId: 'noodle',
          mealTypeId: 'lunch',
          monthlySales: 135,
          rating: 4.6
        }
      ],
      
      // 分页和加载状态
      page: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      
      // 购物车
      cartItems: [],
      cartTotal: 0,
      cartItemCount: 0
    }
  },
  onLoad() {
    // 初始化加载
    this.loadFoodList();
    
    // 检查购物车状态
    this.loadCartFromStorage();
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 前往订单页面
    goToOrders() {
      uni.navigateTo({
        url: '/pages/life/orders/index'
      });
    },
    
    // 搜索输入事件
    onSearchInput(e) {
      this.searchKeyword = e.detail.value;
      this.page = 1;
      this.loadFoodList();
    },
    
    // 切换食堂
    switchCanteen(canteenId) {
      this.currentCanteen = canteenId;
      this.page = 1;
      this.loadFoodList();
    },
    
    // 切换餐点类型
    switchMealType(typeId) {
      this.currentMealType = typeId;
      this.page = 1;
      this.loadFoodList();
    },
    
    // 切换食品分类
    switchCategory(categoryId) {
      this.currentCategory = categoryId;
      this.page = 1;
      this.loadFoodList();
    },
    
    // 获取当前分类名称
    getCurrentCategoryName() {
      const category = this.foodCategories.find(item => item.id === this.currentCategory);
      return category ? category.name : '全部';
    },
    
    // 加载食品列表
    loadFoodList() {
      // 防止重复加载
      if (this.loading) return;
      
      this.loading = true;
      
      // 实际应用中这里应该调用接口获取数据
      // 模拟网络请求延迟
      setTimeout(() => {
        // 根据当前筛选条件过滤食品列表
        let filteredList = [...this.foodList];
        
        // 按食堂筛选
        if (this.currentCanteen !== 'all') {
          filteredList = filteredList.filter(item => item.canteenId === this.currentCanteen);
        }
        
        // 按餐点类型筛选
        if (this.currentMealType !== 'all') {
          filteredList = filteredList.filter(item => item.mealTypeId === this.currentMealType);
        }
        
        // 按分类筛选
        if (this.currentCategory !== 'all') {
          filteredList = filteredList.filter(item => item.categoryId === this.currentCategory);
        }
        
        // 按搜索关键词筛选
        if (this.searchKeyword) {
          filteredList = filteredList.filter(item => 
            item.name.includes(this.searchKeyword) || 
            item.description.includes(this.searchKeyword)
          );
        }
        
        // 模拟分页
        this.foodList = filteredList;
        this.hasMore = false; // 模拟数据已全部加载
        this.loading = false;
      }, 500);
    },
    
    // 加载更多
    loadMoreFood() {
      if (!this.hasMore || this.loading) return;
      
      this.page++;
      this.loadFoodList();
    },
    
    // 前往食品详情
    goToFoodDetail(item) {
      uni.navigateTo({
        url: `/pages/life/food/detail?id=${item.id}`
      });
    },
    
    // 添加到购物车
    addToCart(item) {
      // 查找购物车中是否已有该商品
      const existingItemIndex = this.cartItems.findIndex(cartItem => cartItem.id === item.id);
      
      if (existingItemIndex >= 0) {
        // 已有该商品，数量+1
        this.cartItems[existingItemIndex].quantity += 1;
      } else {
        // 添加新商品
        this.cartItems.push({
          id: item.id,
          name: item.name,
          price: item.price,
          imageUrl: item.imageUrl,
          quantity: 1
        });
      }
      
      // 更新购物车总数和总价
      this.updateCartSummary();
      
      // 保存购物车到本地存储
      this.saveCartToStorage();
      
      // 显示提示
      uni.showToast({
        title: '已添加到购物车',
        icon: 'success'
      });
    },
    
    // 更新购物车汇总信息
    updateCartSummary() {
      this.cartItemCount = this.cartItems.reduce((total, item) => total + item.quantity, 0);
      this.cartTotal = this.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0);
    },
    
    // 保存购物车到本地存储
    saveCartToStorage() {
      uni.setStorageSync('foodCart', {
        items: this.cartItems,
        total: this.cartTotal,
        count: this.cartItemCount
      });
    },
    
    // 从本地存储加载购物车
    loadCartFromStorage() {
      const cartData = uni.getStorageSync('foodCart');
      if (cartData) {
        this.cartItems = cartData.items || [];
        this.cartTotal = cartData.total || 0;
        this.cartItemCount = cartData.count || 0;
      }
    },
    
    // 显示购物车详情
    showCart() {
      // 跳转到购物车页面或显示购物车弹窗
      uni.navigateTo({
        url: '/pages/life/food/cart'
      });
    },
    
    // 去结算
    goToCheckout() {
      if (this.cartItemCount === 0) {
        uni.showToast({
          title: '购物车为空',
          icon: 'none'
        });
        return;
      }
      
      uni.navigateTo({
        url: '/pages/life/food/checkout'
      });
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f6f7fb;
}

// 顶部导航
.header {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #4080ff;
  padding: 0 30rpx;
  color: #fff;
  
  .back-btn, .right-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      font-size: 40rpx;
    }
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
  }
}

// 搜索栏
.search-bar {
  height: 80rpx;
  background-color: #fff;
  margin: 20rpx 30rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .search-icon {
    font-size: 36rpx;
    color: #999;
    margin-right: 10rpx;
  }
  
  .search-input {
    flex: 1;
    height: 80rpx;
    font-size: 28rpx;
    color: #333;
  }
}

// 食堂选择标签
.canteen-tabs {
  background-color: #fff;
  white-space: nowrap;
  padding: 0 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .canteen-tab {
    display: inline-block;
    padding: 20rpx 30rpx;
    font-size: 28rpx;
    color: #666;
    position: relative;
    
    &.active {
      color: #4080ff;
      font-weight: bold;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 6rpx;
        background-color: #4080ff;
        border-radius: 3rpx;
      }
    }
  }
}

// 餐点类型
.meal-tabs {
  background-color: #fff;
  white-space: nowrap;
  padding: 0 20rpx 10rpx;
  
  .meal-tab {
    display: inline-block;
    padding: 10rpx 20rpx;
    margin: 10rpx 10rpx 0 0;
    font-size: 24rpx;
    color: #666;
    background-color: #f5f5f5;
    border-radius: 20rpx;
    
    &.active {
      color: #fff;
      background-color: #4080ff;
    }
  }
}

// 食品分类列表容器
.food-category-container {
  display: flex;
  flex: 1;
  margin-top: 20rpx;
  height: calc(100vh - 320rpx);
  
  // 左侧分类导航
  .category-sidebar {
    width: 180rpx;
    background-color: #f6f7fb;
    height: 100%;
    
    .category-item {
      padding: 30rpx 20rpx;
      font-size: 26rpx;
      color: #666;
      text-align: center;
      position: relative;
      
      &.active {
        color: #4080ff;
        font-weight: bold;
        background-color: #fff;
        
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 6rpx;
          height: 36rpx;
          background-color: #4080ff;
          border-radius: 0 3rpx 3rpx 0;
        }
      }
    }
  }
  
  // 右侧食品列表
  .food-list-scroll {
    flex: 1;
    background-color: #fff;
    height: 100%;
    
    .category-title {
      padding: 20rpx 30rpx;
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      border-bottom: 1rpx solid #f0f0f0;
    }
    
    .food-list {
      padding: 0 30rpx;
      
      .food-item {
        display: flex;
        padding: 30rpx 0;
        border-bottom: 1rpx solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .food-image {
          width: 180rpx;
          height: 180rpx;
          border-radius: 10rpx;
          margin-right: 20rpx;
        }
        
        .food-info {
          flex: 1;
          position: relative;
          
          .food-name {
            font-size: 30rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 10rpx;
          }
          
          .food-tags {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 10rpx;
            
            .food-tag {
              font-size: 20rpx;
              color: #ff6b00;
              background-color: rgba(255, 107, 0, 0.1);
              padding: 2rpx 10rpx;
              border-radius: 4rpx;
              margin-right: 10rpx;
            }
          }
          
          .food-desc {
            font-size: 24rpx;
            color: #999;
            margin-bottom: 20rpx;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          
          .food-bottom {
            display: flex;
            align-items: center;
            
            .food-price {
              font-size: 30rpx;
              color: #ff6b00;
              font-weight: bold;
              margin-right: 20rpx;
            }
            
            .food-sales {
              font-size: 22rpx;
              color: #999;
            }
          }
          
          .add-btn {
            position: absolute;
            right: 0;
            bottom: 0;
            width: 60rpx;
            height: 60rpx;
            background-color: #4080ff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .iconfont {
              font-size: 40rpx;
              color: #fff;
            }
          }
        }
      }
    }
    
    .loading-more, .no-more {
      text-align: center;
      font-size: 24rpx;
      color: #999;
      padding: 20rpx 0;
    }
    
    .empty-list {
      padding: 80rpx 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      
      .empty-image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 20rpx;
      }
      
      text {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}

// 购物车
.cart-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .cart-info {
    flex: 1;
    display: flex;
    align-items: center;
    
    .cart-icon-wrapper {
      position: relative;
      margin-right: 10rpx;
      
      .iconfont {
        font-size: 50rpx;
        color: #4080ff;
      }
      
      .cart-badge {
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        min-width: 36rpx;
        height: 36rpx;
        line-height: 36rpx;
        background-color: #ff4d4f;
        border-radius: 18rpx;
        color: #fff;
        font-size: 20rpx;
        text-align: center;
        padding: 0 6rpx;
      }
    }
    
    .cart-price {
      font-size: 32rpx;
      font-weight: bold;
      color: #ff6b00;
    }
  }
  
  .checkout-btn {
    width: 220rpx;
    height: 80rpx;
    background-color: #4080ff;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    text {
      font-size: 28rpx;
      color: #fff;
      font-weight: bold;
    }
  }
}
</style> 